package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import DAO.*;
import model.*;

public class QueStudy_StudyController extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			processRequest(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		try {
			processRequest(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String uri = request.getRequestURI();
		// String command = uri.substring(uri.lastIndexOf("/")+1,
		// uri.lastIndexOf("/studySearch"));
		String command = uri.substring(uri.lastIndexOf("/") + 1);

		ActionForward forward = null;
		Action action = null;

		if (command != null && command.trim().equals("New.Study")) {

			StudyDao studyDao = new StudyDao();
			DepositDao depositDao = new DepositDao();
			FineDao fineDao = new FineDao();

			HttpSession session = request.getSession();

			if (session.getAttribute("userid") == null
					|| session.getAttribute("userid") == "") {
				session.invalidate();
				Util.ShowError(response, "로그인해주세요");
			} else {
				request.setAttribute("categories", studyDao.getAllCategory());
				request.setAttribute("deposit", depositDao.getAllDeposit());
				request.setAttribute("fine", fineDao.getAllFine());

				forward = new ActionForward();
				forward.setPath("/makeStudy.jsp");
			}

		} else if (command != null && command.trim().equals("Manage.Study")) {

			StudyDao studyDao = new StudyDao();
			boolean isOwn = false;
			HttpSession session = request.getSession();

			int studyId = request.getParameter("studyId") != null
					&& request.getParameter("studyId") != "" ? Integer
					.parseInt(request.getParameter("studyId")) : 0;
			if (studyId == 0) {
				Util.ShowError(response, "잘못 된 접근입니다");
			}

			request.setAttribute("studyId", studyId);

			int userId = session.getAttribute("userid") != null ? Integer
					.parseInt((String) session.getAttribute("userid")) : 0;

			if (studyId < 1 || userId < 1) {
				session.invalidate();
				Util.ShowError(response, "로그인하세요");
			}

			if (userId == studyDao.getStudyInfo(studyId).getUid()) {
				isOwn = true;
			}

			request.setAttribute("isOwn", isOwn);

			forward = new ActionForward();
			forward.setPath("/manageStudy.jsp");

		} else if (command != null && command.trim().equals("ShowMem.Study")) {

			StudyDao studyDao = new StudyDao();
			ParticipationDao participationDao = new ParticipationDao();
			UserDao userDao = new UserDao();
			UserDetailDao userDetailDao = new UserDetailDao();
			ArrayList<Participation> participationList = new ArrayList<Participation>();
			ArrayList<User> userList = new ArrayList<User>();
			ArrayList<UserDetail> userDetailList = new ArrayList<UserDetail>();

			HttpSession session = request.getSession();
			
			int studyId = request.getParameter("studyId") != null
					&& request.getParameter("studyId") != "" ? Integer
					.parseInt(request.getParameter("studyId")) : 0;
			int userIdCheck = session.getAttribute("userid") != null
					&& session.getAttribute("userid") != "" ? Integer
					.parseInt((String)session.getAttribute("userid")) : 0;
			if (userIdCheck < 1) {
				session.invalidate();
				Util.ShowError(response, "로그인해주세요");
			}
			if (studyId < 1) {
				Util.ShowError(response, "잘못 된 접근입니다");
			}
			
			

			request.setAttribute("studyId", studyId);

			participationList = participationDao.getSameStudyMember(studyId);
			for (int i = 0; i < participationList.size(); i++) {

				int userId = participationList.get(i).getUid();

				userList.add(userDao.getUserInfo(userId));
				userDetailList.add(userDetailDao.getUserDetailInfo(userId));
			}

			request.setAttribute("userList", userList);
			request.setAttribute("userDetailList", userDetailList);

		
			forward = new ActionForward();
			forward.setPath("/manageStudy_memInfo.jsp");

		} else if (command != null && command.trim().equals("ShowFine.Study")) {

			StudyDao studyDao = new StudyDao();
			DepositDao depositDao = new DepositDao();
			FineDao fineDao = new FineDao();
			UserDao userDao = new UserDao();
			

			HttpSession session = request.getSession();
			
			int studyId = request.getParameter("studyId") != null
					&& request.getParameter("studyId") != "" ? Integer
					.parseInt(request.getParameter("studyId")) : 0;
			int userIdCheck = session.getAttribute("userid") != null
					&& session.getAttribute("userid") != "" ? Integer
					.parseInt((String)session.getAttribute("userid")) : 0;
			if (userIdCheck < 1) {
				session.invalidate();
				Util.ShowError(response, "로그인해주세요");
			}
			if (studyId < 1) {
				Util.ShowError(response, "잘못 된 접근입니다");
			}
			
			
			
			ArrayList<String> memIdList = new ArrayList<String>();
			ParticipationDao participationDao = new ParticipationDao();
		
			StudyFineDao studyFineDao = new StudyFineDao();
			ArrayList<Participation> participationList = participationDao
					.getSameStudyMember(studyId);
			
			int sumTotalQuest=0;
			int deposit = studyDao.getStudyInfo(studyId).getDeposit();
			int currentDeposit=studyDao.getStudyInfo(studyId).getCurrentDeposit();
			float[] myMoney= new float[participationList.size()];
			float sumMyMoney=0;
			
			for (int i = 0; i < participationList.size(); i++) {
				int userId = participationList.get(i).getUid();
				
				StudyFine studyFine = studyFineDao.getStudyFineInfo(studyId, userId);
				sumTotalQuest+=studyFine.getMyTotalQuest();
				
				System.out.println("0단계"+i+":"+studyFineDao.getReturnByTotalQuest(studyId, userId));
				
				myMoney[i]=studyFineDao.getReturnByTotalQuest(studyId, userId)*(float)deposit;
			
				sumMyMoney+=myMoney[i];
				memIdList.add(userDao.getUserInfo(userId).getMemid());
				System.out.println("1단계"+i+":"+myMoney[i]);
				
			}
			
			for (int i = 0; i < participationList.size(); i++) {
				int userId = participationList.get(i).getUid();
				
				StudyFine studyFine = studyFineDao.getStudyFineInfo(studyId, userId);
				myMoney[i]+=(currentDeposit-sumMyMoney)*studyFine.getMyTotalQuest()/sumTotalQuest;
				System.out.println(i+":"+myMoney[i]);
				
			}

			request.setAttribute("studyId", studyId);
			request.setAttribute("myMoney", myMoney);
			request.setAttribute("memIdList", memIdList);
			request.setAttribute("deposit",deposit);

			forward = new ActionForward();
			forward.setPath("/manageStudy_fine.jsp");

		}

		else if (command != null && command.trim().equals("Accept.Study")) {

			StudyDao studyDao = new StudyDao();
			ParticipationDao participationDao = new ParticipationDao();
			FineDao fineDao = new FineDao();
			ArrayList <Participation> participationList = new ArrayList <Participation>();

			HttpSession session = request.getSession();
			
			int studyId = request.getParameter("studyId") != null
					&& request.getParameter("studyId") != "" ? Integer
					.parseInt(request.getParameter("studyId")) : 0;
			int userIdCheck = session.getAttribute("userid") != null
					&& session.getAttribute("userid") != "" ? Integer
					.parseInt((String)session.getAttribute("userid")) : 0;
			if (userIdCheck < 1) {
				session.invalidate();
				Util.ShowError(response, "로그인해주세요");
			}
			if (studyId < 1) {
				Util.ShowError(response, "잘못 된 접근입니다");
			}
			
			participationList = participationDao.getSameStudyPotentialMember(studyId);
			UserDao userDao = new UserDao();
			ArrayList <String> memIdList = new ArrayList <String>();
			
			for(int i=0; i<participationList.size();i++)
			{
				int userId = participationList.get(i).getUid();
				memIdList.add(userDao.getUserInfo(userId).getMemid());
			}
			
			request.setAttribute("participationList", participationList);
			request.setAttribute("studyId", studyId);
			request.setAttribute("memIdList", memIdList);
			
			forward = new ActionForward();
			forward.setPath("/manageStudy_allow.jsp");

		} else if (command != null && command.trim().equals("NewAction.Study")) {
			action = new StudyNewAction();
			try {

				forward = action.execute(request, response);

			} catch (Exception e) {
				e.printStackTrace();
			}

		} else if (command != null && command.trim().equals("List.Study")) {

			action = new StudyListAction();
			try {

				forward = action.execute(request, response);

			} catch (Exception e) {
				e.printStackTrace();
			}

		} else if (command != null && command.trim().equals("Info.Study")) {
			action = new StudyInfoAction();
			try {

				forward = action.execute(request, response);

			} catch (Exception e) {
				e.printStackTrace();
			}

		} else if (command != null
				&& command.trim().equals("ApplyAction.Study")) {
			action = new StudyApplyAction();
			try {

				forward = action.execute(request, response);

			} catch (Exception e) {
				e.printStackTrace();
			}

		} else if (command != null
				&& command.trim().equals("AcceptAction.Study")) {
			action = new StudyAcceptAction();
			try {

				forward = action.execute(request, response);

			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		if (forward != null) {
			if (forward.isRedirect()) {
				response.sendRedirect(forward.getPath());

			} else {
				RequestDispatcher dispatcher = request
						.getRequestDispatcher(forward.getPath());

				dispatcher.forward(request, response);
			}
		}
	}
}
